/**
 * 应用数据管理的组合式函数
 * 处理文件夹和笔记的CRUD操作
 */

import { reactive } from 'vue'
import { FolderAPI, NoteAPI, OfflineManager } from '../services/crudApi'
import { authState } from '../services/auth'
import { formatDateTime } from '../utils/dateUtils'
import { showError, showSuccess } from '../services/notification'
import type { AppData, Folder, Note } from '../types'

/**
 * 应用数据管理组合式函数
 */
export function useAppData() {
  // 应用状态
  const appState = reactive<AppData>({
    currentFolder: '全部笔记',
    currentNote: null,
    folders: [
      { id: 1, name: '全部笔记', count: 0, isDefault: true, parentId: null, createdAt: '', updatedAt: '' },
      { id: 2, name: '未分类笔记', count: 0, isDefault: true, parentId: null, createdAt: '', updatedAt: '' }
    ],
    notes: []
  })

  /**
   * 更新文件夹计数
   */
  const updateFolderCounts = (): void => {
    appState.folders.forEach(folder => {
      if (folder.name === '全部笔记') {
        folder.count = appState.notes.length
      } else if (folder.name === '未分类笔记') {
        folder.count = appState.notes.filter(note => note.folderId === folder.id).length
      } else {
        folder.count = appState.notes.filter(note => note.folderId === folder.id).length
      }
    })
  }

  /**
   * 创建新笔记
   */
  const createNewNote = async (noteData: Partial<Note>): Promise<void> => {
    const timeString = formatDateTime()
    
    if (authState.isLoggedIn) {
      // 用户已登录，直接调用API创建
      try {
        const createdNote = await NoteAPI.create({
          title: noteData.title || '未命名文档',
          content: noteData.content || '',
          folderId: noteData.folderId || 1,
          createdAt: timeString,
          updatedAt: timeString,
          tags: noteData.tags || []
        })
        
        if (createdNote) {
          appState.notes.unshift(createdNote)
          appState.currentNote = createdNote
          updateFolderCounts()
          showSuccess('笔记创建成功', '成功')
        }
      } catch (error) {
        console.error('创建笔记失败:', error)
        showError('创建笔记失败', '错误')
      }
    } else {
      // 用户未登录，保存到本地并标记为待同步
      const localNote: Note = {
        id: Date.now(),
        title: noteData.title || '未命名文档',
        content: noteData.content || '',
        folderId: noteData.folderId || 1,
        createdAt: timeString,
        updatedAt: timeString,
        tags: noteData.tags || [],
        syncStatus: 'pending'
      }
      
      appState.notes.unshift(localNote)
      appState.currentNote = localNote
      OfflineManager.addPendingNote(localNote)
      
      // 更新文件夹计数
      updateFolderCounts()
      console.log('笔记已保存到本地，等待同步:', localNote.title)
    }
  }

  /**
   * 创建新文件夹
   */
  const createFolder = async (name: string, parentId?: number | null, isShared?: boolean): Promise<void> => {
    const timeString = formatDateTime()
    
    if (authState.isLoggedIn) {
      // 用户已登录，直接调用API创建
      try {
        const createdFolder = await FolderAPI.create({
          name,
          count: 0,
          isDefault: false,
          isShared: isShared || false,
          parentId: parentId || null,
          createdAt: timeString,
          updatedAt: timeString
        })
        
        if (createdFolder) {
          appState.folders.push(createdFolder)
          showSuccess('文件夹创建成功', '成功')
        }
      } catch (error) {
        console.error('创建文件夹失败:', error)
        showError('创建文件夹失败', '错误')
      }
    } else {
      // 用户未登录，保存到本地并标记为待同步
      const localFolder: Folder = {
        id: Date.now(),
        name,
        count: 0,
        isDefault: false,
        isShared: isShared || false,
        parentId: parentId || null,
        createdAt: timeString,
        updatedAt: timeString,
        syncStatus: 'pending'
      }
      
      appState.folders.push(localFolder)
      OfflineManager.addPendingFolder(localFolder)
      console.log('文件夹已保存到本地，等待同步:', localFolder.name)
    }
  }

  /**
   * 更新文件夹
   */
  const updateFolder = async (folderId: number, updates: Partial<Folder>): Promise<void> => {
    const folder = appState.folders.find(f => f.id === folderId)
    if (!folder) return

    if (authState.isLoggedIn && folder.syncStatus === 'synced') {
      // 用户已登录且文件夹已同步，直接调用API更新
      try {
        const updatedFolder = await FolderAPI.update(folderId, {
          ...updates,
          updatedAt: formatDateTime()
        })
        
        if (updatedFolder) {
          Object.assign(folder, updatedFolder)
          showSuccess('文件夹更新成功', '成功')
        }
      } catch (error) {
        console.error('更新文件夹失败:', error)
        showError('更新文件夹失败', '错误')
      }
    } else {
      // 用户未登录或文件夹未同步，仅更新本地
      Object.assign(folder, {
        ...updates,
        updatedAt: formatDateTime(),
        syncStatus: folder.syncStatus === 'synced' ? 'modified' : 'pending'
      })
      console.log('文件夹已更新到本地，等待同步:', folder.name)
    }
  }

  /**
   * 删除文件夹
   */
  const deleteFolder = async (folderId: number): Promise<void> => {
    const folder = appState.folders.find(f => f.id === folderId)
    if (!folder) return

    if (authState.isLoggedIn && folder.syncStatus === 'synced') {
      // 用户已登录且文件夹已同步，调用API删除
      try {
        const success = await FolderAPI.delete(folderId)
        if (success) {
          // 删除文件夹
          const folderIndex = appState.folders.findIndex(f => f.id === folderId)
          if (folderIndex > -1) {
            appState.folders.splice(folderIndex, 1)
          }
          
          // 将该文件夹下的笔记移动到未分类
          appState.notes.forEach(note => {
            if (note.folderId === folderId) {
              note.folderId = 2 // 未分类笔记
            }
          })
          
          updateFolderCounts()
          showSuccess('文件夹删除成功', '成功')
        }
      } catch (error) {
        console.error('删除文件夹失败:', error)
        showError('删除文件夹失败', '错误')
      }
    } else {
      // 用户未登录或文件夹未同步，仅删除本地
      const folderIndex = appState.folders.findIndex(f => f.id === folderId)
      if (folderIndex > -1) {
        appState.folders.splice(folderIndex, 1)
      }
      
      // 将该文件夹下的笔记移动到未分类
      appState.notes.forEach(note => {
        if (note.folderId === folderId) {
          note.folderId = 2 // 未分类笔记
        }
      })
      
      updateFolderCounts()
      console.log('文件夹已从本地删除:', folder.name)
    }
  }

  /**
   * 更新笔记
   */
  const updateNote = async (noteId: number, updates: Partial<Note>): Promise<void> => {
    const note = appState.notes.find(n => n.id === noteId)
    if (!note) return

    if (authState.isLoggedIn && note.syncStatus === 'synced') {
      // 用户已登录且笔记已同步，调用API更新
      try {
        const updatedNote = await NoteAPI.update(noteId, {
          ...updates,
          updatedAt: formatDateTime()
        })
        
        if (updatedNote) {
          Object.assign(note, updatedNote)
        }
      } catch (error) {
        console.error('更新笔记失败:', error)
        showError('更新笔记失败', '错误')
      }
    } else {
      // 用户未登录或笔记未同步，仅更新本地
      Object.assign(note, {
        ...updates,
        updatedAt: formatDateTime(),
        syncStatus: note.syncStatus === 'synced' ? 'modified' : 'pending'
      })
    }
  }

  /**
   * 删除笔记
   */
  const deleteNote = async (noteId: number): Promise<void> => {
    const note = appState.notes.find(n => n.id === noteId)
    if (!note) return

    if (authState.isLoggedIn && note.syncStatus === 'synced') {
      // 用户已登录且笔记已同步，调用API删除
      try {
        const success = await NoteAPI.delete(noteId)
        if (success) {
          const noteIndex = appState.notes.findIndex(n => n.id === noteId)
          if (noteIndex > -1) {
            appState.notes.splice(noteIndex, 1)
          }
          updateFolderCounts()
          showSuccess('笔记删除成功', '成功')
        }
      } catch (error) {
        console.error('删除笔记失败:', error)
        showError('删除笔记失败', '错误')
      }
    } else {
      // 用户未登录或笔记未同步，仅删除本地
      const noteIndex = appState.notes.findIndex(n => n.id === noteId)
      if (noteIndex > -1) {
        appState.notes.splice(noteIndex, 1)
      }
      updateFolderCounts()
      console.log('笔记已从本地删除:', note.title)
    }
  }

  return {
    appState,
    updateFolderCounts,
    createNewNote,
    createFolder,
    updateFolder,
    deleteFolder,
    updateNote,
    deleteNote
  }
}